<template>
  <div class="content-container">
    <div class="page-header">
      <h2>商品管理</h2>
      <el-button type="primary" @click="handleAdd">新增商品</el-button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-section">
      <el-input
        v-model="searchQuery"
        placeholder="搜索商品名称/描述"
        class="search-input"
        clearable
      />
      <el-select v-model="categoryFilter" placeholder="商品分类" clearable>
        <el-option label="食品" value="食品" />
        <el-option label="保健品" value="保健品" />
        <el-option label="器材" value="器材" />
        <el-option label="服务" value="服务" />
      </el-select>
      <el-select v-model="statusFilter" placeholder="商品状态" clearable>
        <el-option label="上架中" value="上架中" />
        <el-option label="已下架" value="已下架" />
        <el-option label="待审核" value="待审核" />
      </el-select>
    </div>

    <!-- 商品列表 -->
    <el-table :data="filteredProducts" v-loading="loading" border>
      <el-table-column prop="product_id" label="ID" width="80" />
      <el-table-column label="商品图片" width="100">
        <template #default="{ row }">
          <el-image
            :src="row.image_url"
            :preview-src-list="[row.image_url]"
            fit="cover"
            class="product-image"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" min-width="200" />
      <el-table-column prop="category" label="分类" width="100">
        <template #default="{ row }">
          <el-tag>{{ row.category }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格" width="120">
        <template #default="{ row }">
          ¥{{ row.price.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" width="100" />
      <el-table-column prop="sales" label="销量" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="row.status === '上架中' ? 'warning' : 'success'"
              @click="handleToggleStatus(row)"
            >
              {{ row.status === '上架中' ? '下架' : '上架' }}
            </el-button>
            <el-button 
              size="small" 
              type="danger"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑/新增对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑商品' : '新增商品'"
      width="800px"
    >
      <el-form :model="form" label-width="100px" :rules="rules" ref="formRef">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="商品分类" prop="category">
          <el-select v-model="form.category">
            <el-option label="食品" value="食品" />
            <el-option label="保健品" value="保健品" />
            <el-option label="器材" value="器材" />
            <el-option label="服务" value="服务" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number 
            v-model="form.price" 
            :precision="2" 
            :step="0.1" 
            :min="0"
          />
        </el-form-item>
        <el-form-item label="商品库存" prop="stock">
          <el-input-number 
            v-model="form.stock" 
            :min="0" 
            :precision="0"
          />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            rows="4"
          />
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
            class="product-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleImageSuccess"
          >
            <img 
              v-if="form.image_url" 
              :src="form.image_url" 
              class="product-image"
            />
            <el-icon v-else class="product-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品规格">
          <div v-for="(spec, index) in form.specifications" :key="index" class="spec-item">
            <el-input v-model="spec.name" placeholder="规格名称" class="spec-input" />
            <el-input v-model="spec.value" placeholder="规格值" class="spec-input" />
            <el-button 
              type="danger" 
              circle 
              @click="removeSpec(index)"
              :icon="Delete"
            />
          </div>
          <el-button type="primary" @click="addSpec">添加规格</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'

// 数据状态
const loading = ref(false)
const products = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchQuery = ref('')
const categoryFilter = ref('')
const statusFilter = ref('')
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

const form = ref({
  name: '',
  category: '',
  price: 0,
  stock: 0,
  description: '',
  image_url: '',
  specifications: [],
  status: '待审核'
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' }
  ]
}

// 过滤商品列表
const filteredProducts = computed(() => {
  let result = products.value

  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(item => 
      item.name.toLowerCase().includes(query) ||
      item.description?.toLowerCase().includes(query)
    )
  }

  if (categoryFilter.value) {
    result = result.filter(item => item.category === categoryFilter.value)
  }

  if (statusFilter.value) {
    result = result.filter(item => item.status === statusFilter.value)
  }

  return result
})

// 获取状态标签类型
const getStatusType = (status) => {
  const types = {
    '上架中': 'success',
    '已下架': 'info',
    '待审核': 'warning'
  }
  return types[status] || 'info'
}

// 模拟商品数据
const mockProducts = [
  {
    product_id: 1,
    name: '有机全麦面包',
    category: '食品',
    price: 15.80,
    stock: 100,
    sales: 258,
    description: '采用优质有机全麦粉制作，不含防腐剂，健康美味。',
    image_url: 'https://example.com/images/bread.jpg',
    specifications: [
      { name: '重量', value: '500g' },
      { name: '保质期', value: '7天' }
    ],
    status: '上架中'
  },
  {
    product_id: 2,
    name: '维生素D补充剂',
    category: '保健品',
    price: 128.00,
    stock: 50,
    sales: 156,
    description: '帮助钙质吸收，增强免疫力，适合全家服用。',
    image_url: 'https://example.com/images/vitamin.jpg',
    specifications: [
      { name: '规格', value: '60片/瓶' },
      { name: '用法', value: '每日1片' }
    ],
    status: '上架中'
  },
  {
    product_id: 3,
    name: '瑜伽垫',
    category: '器材',
    price: 199.00,
    stock: 30,
    sales: 89,
    description: '环保TPE材质，防滑耐用，含背带便于携带。',
    image_url: 'https://example.com/images/yoga-mat.jpg',
    specifications: [
      { name: '尺寸', value: '183x61cm' },
      { name: '厚度', value: '6mm' }
    ],
    status: '上架中'
  },
  {
    product_id: 4,
    name: '私教课程',
    category: '服务',
    price: 299.00,
    stock: 20,
    sales: 45,
    description: '一对一专业指导，定制个性化训练计划。',
    image_url: 'https://example.com/images/personal-training.jpg',
    specifications: [
      { name: '时长', value: '60分钟/节' },
      { name: '有效期', value: '3个月' }
    ],
    status: '待审核'
  },
  {
    product_id: 5,
    name: '蓝莓酵素粉',
    category: '保健品',
    price: 168.00,
    stock: 80,
    sales: 234,
    description: '天然发酵，改善肠道健康，促进新陈代谢。',
    image_url: 'https://example.com/images/enzyme.jpg',
    specifications: [
      { name: '净含量', value: '300g' },
      { name: '食用方法', value: '每日2次' }
    ],
    status: '上架中'
  },
  {
    product_id: 6,
    name: '智能体脂秤',
    category: '器材',
    price: 299.00,
    stock: 45,
    sales: 167,
    description: '高精度传感器，多项身体指标监测，APP数据同步。',
    image_url: 'https://example.com/images/scale.jpg',
    specifications: [
      { name: '尺寸', value: '300x300mm' },
      { name: '电池规格', value: '4节AAA电池' }
    ],
    status: '已下架'
  },
  {
    product_id: 7,
    name: '有机奇亚籽',
    category: '食品',
    price: 49.90,
    stock: 150,
    sales: 423,
    description: '富含omega-3，膳食纤维的优质营养食品。',
    image_url: 'https://example.com/images/chia.jpg',
    specifications: [
      { name: '产地', value: '澳大利亚' },
      { name: '规格', value: '250g/袋' }
    ],
    status: '上架中'
  },
  {
    product_id: 8,
    name: '瑜伽课程套餐',
    category: '服务',
    price: 1288.00,
    stock: 30,
    sales: 12,
    description: '专业瑜伽教练指导，提供个性化训练计划。',
    image_url: 'https://example.com/images/yoga-class.jpg',
    specifications: [
      { name: '课时', value: '12节课' },
      { name: '有效期', value: '6个月' }
    ],
    status: '待审核'
  },
  {
    product_id: 9,
    name: '蛋白质能量棒',
    category: '食品',
    price: 12.90,
    stock: 500,
    sales: 1267,
    description: '健身能量补充，便携营养代餐。',
    image_url: 'https://example.com/images/protein-bar.jpg',
    specifications: [
      { name: '重量', value: '45g/条' },
      { name: '口味', value: '巧克力' }
    ],
    status: '上架中'
  },
  {
    product_id: 10,
    name: '跑步机',
    category: '器材',
    price: 3999.00,
    stock: 10,
    sales: 28,
    description: '静音电动跑步机，多功能LED显示，可折叠收纳。',
    image_url: 'https://example.com/images/treadmill.jpg',
    specifications: [
      { name: '最大承重', value: '120kg' },
      { name: '速度范围', value: '1-16km/h' }
    ],
    status: '上架中'
  },
  {
    product_id: 11,
    name: '胶原蛋白粉',
    category: '保健品',
    price: 268.00,
    stock: 60,
    sales: 189,
    description: '深海鱼胶原蛋白，改善肌肤状态。',
    image_url: 'https://example.com/images/collagen.jpg',
    specifications: [
      { name: '净含量', value: '200g' },
      { name: '适用人群', value: '成年人' }
    ],
    status: '上架中'
  },
  {
    product_id: 12,
    name: '营养咨询服务',
    category: '服务',
    price: 499.00,
    stock: 15,
    sales: 8,
    description: '专业营养师一对一指导，定制饮食方案。',
    image_url: 'https://example.com/images/nutrition.jpg',
    specifications: [
      { name: '服务时长', value: '90分钟' },
      { name: '服务方式', value: '线上视频' }
    ],
    status: '待审核'
  }
]

// 模拟API调用
const getProductList = async () => {
  // 模拟API延迟
  await new Promise(resolve => setTimeout(resolve, 500))
  return {
    data: mockProducts,
    total: mockProducts.length
  }
}

const createProduct = async (productData) => {
  await new Promise(resolve => setTimeout(resolve, 500))
  const newProduct = {
    ...productData,
    product_id: mockProducts.length + 1,
    sales: 0
  }
  mockProducts.push(newProduct)
  return newProduct
}

const updateProduct = async (productData) => {
  await new Promise(resolve => setTimeout(resolve, 500))
  const index = mockProducts.findIndex(p => p.product_id === productData.product_id)
  if (index !== -1) {
    mockProducts[index] = { ...mockProducts[index], ...productData }
    return mockProducts[index]
  }
  throw new Error('商品不存在')
}

const deleteProduct = async (productId) => {
  await new Promise(resolve => setTimeout(resolve, 500))
  const index = mockProducts.findIndex(p => p.product_id === productId)
  if (index !== -1) {
    mockProducts.splice(index, 1)
    return true
  }
  throw new Error('商品不存在')
}

const toggleProductStatus = async (productId) => {
  await new Promise(resolve => setTimeout(resolve, 500))
  const product = mockProducts.find(p => p.product_id === productId)
  if (product) {
    product.status = product.status === '上架中' ? '已下架' : '上架中'
    return product
  }
  throw new Error('商品不存在')
}

// 处理方法
const handleAdd = () => {
  isEdit.value = false
  form.value = {
    name: '',
    category: '',
    price: 0,
    stock: 0,
    description: '',
    image_url: '',
    specifications: [],
    status: '待审核'
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  form.value = { ...row }
  dialogVisible.value = true
}

const handleSave = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (isEdit.value) {
      await updateProduct(form.value)
    } else {
      await createProduct(form.value)
    }
    
    ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
    dialogVisible.value = false
    handleRefresh()
  } catch (error) {
    ElMessage.error(error.message || '操作失败，请重试')
  }
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除商品"${row.name}"吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteProduct(row.product_id)
      ElMessage.success('删除成功')
      handleRefresh()
    } catch (error) {
      ElMessage.error(error.message || '删除失败')
    }
  })
}

const handleToggleStatus = (row) => {
  const action = row.status === '上架中' ? '下架' : '上架'
  ElMessageBox.confirm(
    `确定要${action}商品"${row.name}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await toggleProductStatus(row.product_id)
      ElMessage.success(`${action}成功`)
      handleRefresh()
    } catch (error) {
      ElMessage.error(error.message || `${action}失败`)
    }
  })
}

const handleImageSuccess = (response) => {
  form.value.image_url = response.url
}

const addSpec = () => {
  form.value.specifications.push({ name: '', value: '' })
}

const removeSpec = (index) => {
  form.value.specifications.splice(index, 1)
}

const handleRefresh = async () => {
  loading.value = true
  try {
    const response = await getProductList()
    products.value = response.data
    total.value = response.total
    loading.value = false
  } catch (error) {
    ElMessage.error('获取商品列表失败')
    loading.value = false
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  handleRefresh()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  handleRefresh()
}

// 添加页面加载时自动获取商品列表
onMounted(() => {
  handleRefresh()
})
</script>

<style scoped>
.content-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-section {
  margin-bottom: 20px;
  display: flex;
  gap: 15px;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.product-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

.product-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.product-uploader:hover {
  border-color: #409eff;
}

.product-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.spec-item {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
  align-items: center;
}

.spec-input {
  width: 200px;
}
</style> 